import { defineStore } from 'pinia';
import useUserStore from './useUserStore';
import useVoiceCallStore from "./useVoiceCallStore";
import config from '@/config/app-config';
import useRouter from '@/hooks/useRouter';
import type { IMessageModel, IConversationModel } from '@tencentcloud/chat-uikit-engine';
import useTencentIm from '@/hooks/useTencentIm';
import api, { sendMsg } from '@/api/index.ts';
import WxPay from "@/libs/WxPay";
const tencentIm = useTencentIm();
type IMSTore = {
	// 会话列表
	conversationList ?: IConversationModel[];
	// 信息列表
	messageList ?: IMessageModel[];
	// 是否漫游加载完成
	isCompleted ?: boolean;
	// 当前会话id
	currentConversationID ?: any;
	// 当前会话信息
	currentConversation ?: any;
	friendList ?: any;
	// 锁是否开启
	isLock ?: boolean;
	// 是否初始化
	isInitialized ?: boolean;
	isFirstGetFriend ?: boolean;
	getConversation ?: boolean;
	friendUid ?: string | null;
	friendUuid ?: string | null;
	isSending ?: boolean;
	sendMsgData ?: IMessageModel;
	doImIng ?: boolean;
	SDKAppID : number;
	secretKey : string;
};
// TODO 没有对接 远程消息缓存 因 数据格式与 im 不一致
const useImStore = defineStore('im-store', {
	persist: {
		paths: ['currentConversationID', 'currentConversation', 'friendList', 'friendUid', 'friendUuid']
	},
	state: () : IMSTore => ({
		conversationList: [], // 会话列表，用于展示会话列表。
		messageList: [], // 信息列表，用于展示会话信息。
		isCompleted: false,
		currentConversationID: null, // 当前会话id，用于展示会话信息。
		currentConversation: null, // 当前会话信息，用于展示会话列表。
		isLock: false,
		isInitialized: false,
		friendList: [],
		isFirstGetFriend: true,
		getConversation: true,
		friendUid: null,
		friendUuid: null,
		isSending: false,
		sendMsgData: null,
		doImIng: false,
		SDKAppID: 1600035983, // Your SDKAppID
		secretKey: "4d2d882033594899ed47528b62f6b390937975918c114fff057985d9b507f383", // Your secretKey

	}),

	getters: {},

	actions: {
		login() {
			if (!this.isLock) {
				// Store 加锁 确保重新更新用户信息 不重复登录
				const user = useUserStore();
				const voiceCallStore = useVoiceCallStore();
				this.isLock = true; // 初始化IMStore，用于初始化IMStore的初始状态。
				this.isInitialized = false;
				if (this.isInitialized) {
					this.updateMyProfile();
				} else {
					console.log("user", user)
					const res = tencentIm.login({
						userID: user.uuid,
						SDKAppID: this.SDKAppID,
						secretKey: this.secretKey,
					});
					res.then((data) => {
						this.isInitialized = true;
						this.isLock = false;
						this.updateMyProfile();
						tencentIm.watchChatNew({
							newMessageList: (list : any) => {
								const page = getCurrentPages();
								for (let i = 0; i < list.length; i++) {
									let item = list[i];
									if (item.flow === 'in' && !item.isRead) {
										// 存在通话 自动发送忙线信息
										let payload = item.payload;
										let extension = JSON.parse(payload.extension);
										console.log(extension, voiceCallStore.currentCall)
										if (item.payload.data === 'voice-call') {
											if (extension.show == 'false' && extension.roomId !== voiceCallStore.currentCallRoomId) {
												// 特殊处理 语音通话消息
												// 没有通话时弹出 
												if (!voiceCallStore.isCallIng) {
													uni.$emit('on-voice-call', {
														...item,
														in: true,
													});
												} else {
													let data = {
														data: 'voice-call',
														description: '',
														extension: JSON.stringify({
															roomId: extension.roomId,
															text: "暂时忙线",
															show: 'true'
														})
													}
													this.sendMessage(data, 'custom', item.from)
													voiceCallStore.editCallStoreData({
														isCallIng: false
													});
													voiceCallStore.stopVoiceCallAudio();
													uni.$emit('on-voice-call-end', {});
												}
											} else {
												if (extension.text === '无答应' || extension.text === '暂时忙线' || extension.text === '已拒绝' || extension.text === '已取消' || extension.text.indexOf('通话时常') !== -1) {
													voiceCallStore.editCallStoreData({
														isCallIng: false
													});
													voiceCallStore.stopVoiceCallAudio();
													uni.$emit('on-voice-call-end', {});
													uni.$emit('on-voice-call-exit-room', 2);
												}
											}
										} else if (page[page.length - 1].route !== 'im/chat/chat') {
											uni.$wdToast.showNotify('primary', '您有一条新的消息，请即时查看');
										} else if (item.conversationID !== this.currentConversationID) {
											uni.$wdToast.showNotify('primary', '您有一条新的消息，请即时查看');
										}
									}
								}
							}
						});
					}).catch((err) => {
						this.isLock = false;
						console.error('登录失败IM', err);
					});
				}
			}
		},
		updateMyProfile() {
			if (this.isInitialized) {
				const user = useUserStore();
				tencentIm.updateMyProfile({
					name: user.realname || user.username,
					head: user.head || 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uni-app.png'
				});
			}
		},
		// 销毁 im sdk
		destroy() {
			if (this.isInitialized) {
				tencentIm.destroy();
			}
		},
		// 切换会话，用于切换会话。
		switchConversation(conversationID ?: string) {
			if (this.isInitialized) {
				if (conversationID) {
					tencentIm.switchConversation(conversationID);
					this.$patch({
						currentConversationID: conversationID
					});
				} else {
					tencentIm.switchConversation(this.currentConversationID);
				}
			}
		},


		getConversationProfile(currentConversationID ?: string) {
			if (this.isInitialized) {
				return tencentIm.getConversationProfile(currentConversationID ?? this.currentConversationID)
			}
		},
		getFriend(friendId ?: string) {
			if (this.isInitialized) {
				return tencentIm.getFriend(friendId)
			}
		},
		async toFriendChat(friendId : any, userId : any, uuid : any) {
			this.$patch({
				friendUid: userId,
				friendUuid: uuid
			});
			if (friendId) {
				let res = await tencentIm.toFriendChat(friendId);
				this.$patch({
					currentConversationID: res.conversationID,
					currentConversation: res
				});
				return res;
			}
			return null;

		},
		checkFriend(friendId : any) {
			return tencentIm.checkFriend(friendId);
		},

		// 新增好友
		async addFriend(friendId : string, askOrderId ?: any, uid ?: number, OType = 'ask') {
			try {
				let res = await tencentIm.checkFriend(friendId); // 第一个参数是好友ID，第二个参数是验证信息，可以为空字符串。
				if (res.data.successUserIDList.length > 0) {
					await tencentIm.deleteFriend(friendId);
				}
				const friend = await tencentIm.addFriend(friendId);
				setTimeout(() => {
					tencentIm.updateFriend(friendId, [
						// 好友自定义字段必须以 Tag_SNS_Custom 为前缀
						{ key: 'Tag_SNS_Custom_AOrderId', value: String(askOrderId) },
						{ key: 'Tag_SNS_Custom_OType', value: String(OType) },
						{ key: 'Tag_SNS_Custom_Uid', value: String(uid) }
					]);
				}, 100)
				return friend;
			} catch (error) {
				return Promise.reject(error);
				console.error(error.code, 'error'); // 输出：{ code: 10011, message: 'friend not found' }
			}
		},

		// 重新发送信息。
		resendMessage(item : any) {
			tencentIm.resendMessage(item);
		},
		// 发送信息
		async sendMessage(payload : any, type : string, to ?: string) {
			let options = {
				to: to ?? (this.currentConversation?.groupProfile?.groupID || this.currentConversation?.userProfile?.userID),
				conversationType: (this.currentConversation && this.currentConversation.type) || tencentIm.TYPES.CONV_C2C,
				needReadReceipt:
					tencentIm.TUIStore.getData(tencentIm.StoreName.USER, 'displayMessageReadReceipt') &&
					tencentIm.TUIStore.getData(tencentIm.StoreName.APP, 'enabledMessageReadReceipt'),
				payload,
				type
			};

			let res = await tencentIm.sendMessage(options);
			if (res.code !== 0 && !res.data.message) {
				return false;
			}
			let data = {};
			try {
				if (type == 'custom' && payload.data == 'order') {
					type = 'order';
				} else if (type == 'custom' && payload.data == 'voice-call') {
					type = 'voice-call';
				}
				data = {
					msg_type: type,
					receive_user_id: this.friendUid,
					msg_content: JSON.stringify({
						...res.data.message,
						...payload
					}),
				};
				sendMsg(data);
			} catch (error) {
				console.error(error);
			}
			this.$patch({
				sendMsgData: data,
				isSending: true,
			});
			return res;
		},

		// 去去支付
		doPayment(orderId : any) {
			api.queryPayStatus({ ask_order_id: orderId }).then((res : any) => {
				if (res.is_pay === 1) {
					this.getOrderLawyer(orderId);
				} else {
					let wxPay = new WxPay();
					console.log(wxPay, 'wxPay')
					wxPay.pay({
						orderId: orderId,
						type: 1
					}, {
						getOrderCb: () => {
							this.getOrderLawyer(orderId);
						}
					})
				}
			})

		},
		// 查询订单状态
		getOrder(orderId : any) {
			api.queryPayStatus({ ask_order_id: orderId }).then((res : any) => {
				if (res.is_pay === 1) {
					this.getOrderLawyer(orderId);
				} else {
					this.getOrder(orderId);
				}
			})
		},
		// 获取订单律师
		getOrderLawyer(orderId : any) {
			api.queryAssignLawyer({ ask_order_id: orderId }).then((res : any) => {
				this.getLawyerUuid(res.lawyer_id, orderId);
			})
		},
		getLawyerUuid(lawyerId : any, orderId : any) {
			if (!lawyerId) {
				uni.$wdToast.error("当前未分配律师，请联系管理员")
				this.$patch({
					doImIng: false,
				});
				return
			}
			const router = useRouter();
			api.getProfileById({ user_id: lawyerId }).then((res : any) => {
				this.addFriend(res.uuid, res.uid, orderId).then(async () => {
					const friend = await this.toFriendChat(res.uuid, res.uid, res.uuid);
					const dd = await this.sendMessage({ text: `您好，我有个法律问题想咨询您一下` }, 'text', res.uuid)

					router.push({
						url: "/im/chat/chat",
						params: {
							uuid: res.uuid,
						}
					});
					this.$patch({
						doImIng: false,
					});
				}).catch((error : any) => {
					this.$patch({
						doImIng: false,
					});
					if (error.code === 30003) {
						uni.$wdToast.error("系统分配用户暂未上线，请联系管理员")
					}
				})


			})
		},
		doIm(imTypeid : any, lawyer : any) {
			if (this.doImIng) {
				return false;
			}
			this.$patch({
				doImIng: true,
			});
			api.submitOrder({
				ask_type_id: imTypeid,
				lawyer_id: lawyer,
				is_agreen: 1,
			}).then(res => {
				this.doPayment(res.order_id);
			});
		}

	}
});

export default useImStore;